﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CKFinder;
using System.Data;

public partial class Admin_EditProduct : System.Web.UI.Page
{
    ColorsController colorsController = new ColorsController();
    CategoryController categoryController = new CategoryController();
    TinhnangController tinhnangController = new TinhnangController();
    HDSudungController hdSudungController = new HDSudungController();
    NewsController newsController = new NewsController();
    PhukienController pPhukienController = new PhukienController();
    ProductsController productsController = new ProductsController();
    AddressController addressController = new AddressController();
    AddressBaohanhController addressBaohanhController = new AddressBaohanhController();
    GroupTinhnangController groupTinhnangController = new GroupTinhnangController();
    BaohanhController baohanhController = new BaohanhController();
    ProductImageController productImageController = new ProductImageController();
    DanhmucsanphamController dmsp = new DanhmucsanphamController();
    public List<GroupTinhnang> listGroupTinhnang = new GroupTinhnangController().getAllGroup();
    public List<Tinhnang> listTinhnang = new TinhnangController().getAllTinhnang();
    public Products product = null;
    public List<ProductImage> product_images = new List<ProductImage>();
    protected void Page_Load(object sender, EventArgs e)
    {
        ckeditor_description.config.toolbar = "Basic";
        ckeditor_tinhnangnoibat.config.toolbar = "Basic";
        ckeditor_tinhnangkhac.config.toolbar = "Basic";
        CKFinder.FileBrowser fb = new FileBrowser();
        fb.BasePath = "../ckfinder/";
        fb.SetupCKEditor(ckeditor_description);
        fb.SetupCKEditor(ckeditor_tinhnangnoibat);
        fb.SetupCKEditor(ckeditor_tinhnangkhac);
        if (!IsPostBack)
        {
            //Color
            lstColor.DataSource = colorsController.GetAll();
            lstColor.DataTextField = "name";
            lstColor.DataValueField = "color_id";
            lstColor.DataBind();
            ddlCategory_1.DataSource = categoryController.getAllCategory();
            ddlCategory_1.DataTextField = "name";
            ddlCategory_1.DataValueField = "category_id";
            ddlCategory_1.DataBind();


            //Address
            lstAddress.DataSource = addressController.GetAll();
            lstAddress.DataTextField = "title";
            lstAddress.DataValueField = "address_id";
            lstAddress.DataBind();
            //HDSD
            lstHDSD.DataSource = hdSudungController.GetAll();
            lstHDSD.DataTextField = "title";
            lstHDSD.DataValueField = "HD_id";
            lstHDSD.DataBind();
            //News
            lstNews.DataSource = newsController.GetAll();
            lstNews.DataTextField = "title";
            lstNews.DataValueField = "news_id";
            lstNews.DataBind();
            //Phu kien
            lstPhukien.DataSource = pPhukienController.GetAll();
            lstPhukien.DataTextField = "name";
            lstPhukien.DataValueField = "phukien_id";
            lstPhukien.DataBind();
            //Relate

            lstRelate.DataSource = productsController.GetAll();
            lstRelate.DataTextField = "model";
            lstRelate.DataValueField = "product_id";
            lstRelate.DataBind();

            //Dia chi bao hanh
            ddlAddressBaohanh.DataSource = addressBaohanhController.getAllAddressBaohanh();
            ddlAddressBaohanh.DataTextField = "content";
            ddlAddressBaohanh.DataValueField = "address_baohanh_id";
            ddlAddressBaohanh.DataBind();

            //Bao hanh
            ddlBaohanh.DataSource = baohanhController.GetAll();
            ddlBaohanh.DataTextField = "title";
            ddlBaohanh.DataValueField = "baohanh_id";
            ddlBaohanh.DataBind();

            //Loai danh muc
            lstLoaidanhmuc.DataSource = dmsp.GetAll();
            lstLoaidanhmuc.DataTextField = "name";
            lstLoaidanhmuc.DataValueField = "danhmuc_id";
            lstLoaidanhmuc.DataBind();

            string id = Request.QueryString["id"];

            if (id != "" && id != null && !string.IsNullOrWhiteSpace(id) && !string.IsNullOrEmpty(id))
            {
                int idd = Convert.ToInt32(id);
                if (checkId(idd))
                {
                    DataTable dt = productsController.GetByID(idd);
                    product = new Products(dt.Rows[0]);
                    txtModel.Text = product.Model;
                    txtUrl.Text = product.Url;
                    ddlCategory_1.Items.FindByValue(product.Category_id + "").Selected = true;
                    img_product.ImageUrl = ResolveUrl("~/") + product.Image;
                    product_value.Value = product.Image;
                    ckeditor_description.Text = product.Description;
                    txtTag.Text = product.Tag;
                    txtPriceInputs.Text = product.Price_input + "";
                    txtPriceOutputs.Text = product.Price_output + "";
                    txtQuantity.Text = product.Quantity + "";
                    ddlAddressBaohanh.Items.FindByValue(product.AddressBaohanh_id + "").Selected = true;
                    ddlBaohanh.Items.FindByValue(product.Baohanh_id + "").Selected = true;
                    if (product.Top)
                    {
                        chkTop.Checked = true;
                    }
                    else
                    {
                        chkTop.Checked = false;
                    }
                    if (product.Status)
                    {
                        ddlStatus.SelectedIndex = 0;
                    }
                    else
                    {
                        ddlStatus.SelectedIndex = 1;
                    }
                    DataTable dtColor = colorsController.GetByProductID(idd);
                    foreach (DataRow item in dtColor.Rows)
                    {
                        Colors c = new Colors(item);
                        lstColor.Items.FindByValue(c.Color_id + "").Selected = true;
                    }
                    DataTable dtAddress = addressController.GetByProductID(idd);
                    foreach (DataRow item in dtAddress.Rows)
                    {
                        lstAddress.Items.FindByValue(item[2].ToString()).Selected = true;
                    }
                    DataTable dtHDSD = hdSudungController.GetByProductID(idd);
                    foreach (DataRow item in dtHDSD.Rows)
                    {
                        lstHDSD.Items.FindByValue(item[2].ToString()).Selected = true;
                    }
                    DataTable dtImage = productImageController.GetByProductID(idd);
                    foreach (DataRow item in dtImage.Rows)
                    {
                        ProductImage pi = new ProductImage(item);
                        product_images.Add(pi);
                    }
                    DataTable dtNews = newsController.GetByProductID(idd);
                    foreach (DataRow item in dtNews.Rows)
                    {
                        lstNews.Items.FindByValue(item[0].ToString()).Selected = true;
                    }
                    DataTable dtPhukien = pPhukienController.GetByProductID(idd);
                    foreach (DataRow item in dtPhukien.Rows)
                    {
                        lstPhukien.Items.FindByValue(item[0].ToString()).Selected = true;
                    }
                    DataTable dtRelate = productsController.getProductRelate(idd);
                    foreach (DataRow item in dtRelate.Rows)
                    {
                        lstRelate.Items.FindByValue(item[2].ToString()).Selected = true;
                    }

                    DataTable dtDanhmucsanpham = productsController.getProductDanhmucsanpham(idd);
                    foreach (DataRow item in dtDanhmucsanpham.Rows)
                    {
                        lstLoaidanhmuc.Items.FindByValue(item[2].ToString()).Selected = true;
                    }



                }
                else
                {
                    error();
                }
            }
            else
            {
                error();
            }
        }
        
    }
    public void error()
    {
        Response.Redirect("~/Error.aspx");
    }
    public bool checkId(int id)
    {
        DataTable dt = productsController.GetByID(id);
        if(dt.Rows.Count>0)
        {
            return true;
        }
        return false;
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Products p = new Products();
        //Insert data to Product
        string id = Request.QueryString["id"];
        int idd = Convert.ToInt32(id);
        if(!checkId(idd))
        {
            error();
        }
        else
        {
            p.Product_id = Convert.ToInt32(id);
            p.Model = txtModel.Text;
            p.Url = txtUrl.Text;
            p.Category_id = Convert.ToInt32(ddlCategory_1.SelectedValue);
            p.DateUpdate = DateTime.Now;
            p.Tag = txtTag.Text;
            if (ddlStatus.SelectedIndex == 0)
            {
                p.Status = true;
            }
            else
            {
                p.Status = false;
            }
            p.Price_input = float.Parse(txtPriceInputs.Text);
            p.Price_output = float.Parse(txtPriceOutputs.Text);
            p.Baohanh_id = Convert.ToInt32(ddlBaohanh.SelectedValue);
            p.View = 0;
            p.Top = true;
            if (chkTop.Checked)
                p.Top = false;
            p.AddressBaohanh_id = Convert.ToInt32(ddlAddressBaohanh.SelectedValue);
            p.Quantity = Convert.ToInt32(txtQuantity.Text);
            p.Tinhnangnoibat = ckeditor_tinhnangnoibat.Text;
            p.Trangthaiphathanh = txtTrangthaiphat.Text;
            p.Ngaycongbo = txtNgaycongbo.Text;
            p.Ngayphathanh = txtNgayphatphat.Text;
            p.Bangtan = txtBangtan.Text;
            p.Chieudai = txtChieudai.Text;
            p.Chieurong = txtChieurong.Text;
            p.Chieucao = txtChieucao.Text;
            p.Cannang = txtCannang.Text;
            p.Kieumanhinh = txtKieumanhinh.Text;
            p.Kichthuocmanhinh = txtKichthuocmanhinh.Text;
            p.Dophangiai = txtDophangiai.Text;
            p.Camung = txtCamung.Text;
            p.Tinhnangkhac = ckeditor_tinhnangkhac.Text;
            p.Tinnhan = txtTinnhan.Text;
            p.Jackcam = txtJackcam.Text;
            p.Tainhacchuong = txtTainhacchuong.Text;
            p.Loangoai = txtLoangoai.Text;
            p.Danhbaluutru = txtDanhbaluutru.Text;
            p.Hotrosms = txtHotrosms.Text;
            p.Hotroemail = txtHotroemail.Text;
            p.Bonhotrong = txtBonhotrong.Text;
            p.Dungluongthenho = txtDungluongthenho.Text;
            p.Loaithenho = txtLoaithenho.Text;
            p.Gprs = txtGprs.Text;
            p.Edge = txtEdge.Text;
            p.BaG = txtBag.Text;
            p.Web = txtWeb.Text;
            p.Gps = txtGps.Text;
            p.Bluetooth = txtBluetooth.Text;
            p.Wifi = txtWifi.Text;
            p.Hongngoai = txtHongngoai.Text;
            p.Usb = txtUsb.Text;
            p.Mayanhchinh = txtMayanhchinh.Text;
            p.Mayanhkhac = txtMayanhkhac.Text;
            p.Mayanhphu = txtMayanhphu.Text;
            p.Quayphim = txtQuayphim.Text;
            p.Nghenhac = txtNghenhac.Text;
            p.Xemphim = txtXemphim.Text;
            p.Radio = txtRadio.Text;
            p.Tivi = txtTivi.Text;
            p.Ketnoitivi = txtKetnoitivi.Text;
            p.Ghiam = txtGhiam.Text;
            p.Luutrucuocgoi = txtLuutrucuoigoi.Text;
            p.Ungdungvanphong = txtUngdungvanphong.Text;
            p.Ungdungkhac = txtUngdungkhac.Text;
            p.Trochoi = txtTrochoi.Text;
            p.Hotrosim = txtHotrosim.Text;
            p.Hotrojava = txtHotrojava.Text;
            p.Kieudang = txtKieudang.Text;
            p.Hedieuhanh = txtHedieuhanh.Text;
            p.Phienbanhedieuhanh = txtPhienbanhedieuhanh.Text;
            p.Cpu = txtCpu.Text;
            p.Ram = txtRam.Text;
            p.Ngonngu = txtNgonngu.Text;
            p.Qwerty = txtQwerty.Text;
            p.Hotromang = txtHotromang.Text;
            p.Loaipin = txtLoaipin.Text;
            p.Thoigiancho2g = txtThoigiancho2g.Text;
            p.Thoigiancho3g = txtThoigiancho3g.Text;
            p.Damthoai2g = txtDamthoai2g.Text;
            p.Damthoai3g = txtDamthoai3g.Text;
            p.Dungluongpin = txtDungluongpin.Text;
            p.Image = product_value.Value;
            p.Description = ckeditor_description.Text;
            int check = productsController.Update(p);
            if (check > 0)
            {
                //day la doan code de anh insert color vao database em check xem sao
                //doan add du lieu cho listbox dau anh
                //anh chay va bug em xem phat

                int[] arrayColor = new int[lstColor.Items.Count];
                int j = 0;
                for (int i = 0; i < lstColor.Items.Count; i++)
                {
                    if (lstColor.Items[i].Selected)
                    {
                        arrayColor[j++] = Convert.ToInt32(lstColor.Items[i].Value);
                    }
                }
                productsController.insertProductColor(idd, arrayColor);

                //Add Address
                int[] arrayAddress = new int[lstAddress.Items.Count];
                for (int i = 0; i < lstAddress.Items.Count; i++)
                {
                    if (lstAddress.Items[i].Selected)
                        arrayAddress[i] = Convert.ToInt32(lstAddress.Items[i].Value);
                }
                productsController.insertProductAddress(idd, arrayAddress);

                //Add HDSD
                int[] arrayHDSD = new int[lstHDSD.Items.Count];
                for (int i = 0; i < lstHDSD.Items.Count; i++)
                {
                    if (lstHDSD.Items[i].Selected)
                        arrayHDSD[i] = Convert.ToInt32(lstHDSD.Items[i].Value);
                }
                productsController.insertProductHDSD(idd, arrayHDSD);
                //Add Images
                if (images_values.Value != "")
                {
                    string str = images_values.Value.Substring(1);
                    char[] s = { ',' };
                    string[] image = str.Split(s);
                    foreach (var s1 in image)
                    {
                        ProductImage pi = new ProductImage();
                        pi.Image = s1;
                        pi.Product_id = idd;
                        pi.Order = 1;
                        pi.Status = true;
                        pi.DateStart = DateTime.Now;

                        productImageController.Insert(pi);
                    }
                }

                //Add Product_News
                int[] arrayNews = new int[lstNews.Items.Count];
                for (int i = 0; i < lstNews.Items.Count; i++)
                {
                    if (lstNews.Items[i].Selected)
                        arrayNews[i] = Convert.ToInt32(lstNews.Items[i].Value);
                }
                productsController.insertProductNews(idd, arrayNews);

                //Add Product_Phukien
                int[] arrayPhukien = new int[lstPhukien.Items.Count];
                for (int i = 0; i < lstPhukien.Items.Count; i++)
                {
                    if (lstPhukien.Items[i].Selected)
                        arrayPhukien[i] = Convert.ToInt32(lstPhukien.Items[i].Value);
                }
                productsController.insertProductPhukien(idd, arrayPhukien);

                //Add Product_Relate
                int[] arrayRelate = new int[lstRelate.Items.Count];
                int iRelate = 0;
                for (int i = 0; i < lstRelate.Items.Count; i++)
                {
                    if (lstRelate.Items[i].Selected)
                        arrayRelate[iRelate++] = Convert.ToInt32(lstRelate.Items[i].Value);
                }
                productsController.insertProductRelate(idd, arrayRelate);

                //Add Product_Danhmucsanpham
                int[] arrayDanhmucsanpham = new int[lstLoaidanhmuc.Items.Count];
                int iDanhmucsanpham = 0;
                for (int i = 0; i < lstLoaidanhmuc.Items.Count; i++)
                {
                    if (lstLoaidanhmuc.Items[i].Selected)
                        arrayDanhmucsanpham[iDanhmucsanpham++] = Convert.ToInt32(lstLoaidanhmuc.Items[i].Value);
                }
                productsController.insertProductDanhmucsanpham(idd, arrayDanhmucsanpham);
                Response.Write("<script>alert('Cập nhật thành công')</script>");
                Server.Transfer(Request.RawUrl);
            }
            else
            {
                Response.Write("<script>alert('Cập nhật không thành công')</script>");
                return;
            }
        }
        
    }
}